<template>
  <view class="container">
    <!-- 钱包余额卡片 -->
    <view class="wallet-card">
      <view class="balance-section">
        <view class="balance-title">钱包余额</view>
        <view class="balance-amount">¥{{ userBalance.toFixed(2) }}</view>
        <view class="balance-desc">可用于发布任务和支付服务费</view>
      </view>
      <view class="wallet-actions">
        <button class="action-btn recharge-btn" @tap="showRechargeModal">充值</button>
        <button class="action-btn history-btn" @tap="goToHistory">明细</button>
      </view>
    </view>

    <!-- 任务收入统计 -->
    <view class="income-card">
      <view class="card-title">任务收入统计</view>
      <view class="income-section">
        <view class="income-item">
          <view class="income-label">累计收入</view>
          <view class="income-amount">¥{{ totalIncome.toFixed(2) }}</view>
        </view>
        <view class="income-item">
          <view class="income-label">本月收入</view>
          <view class="income-amount">¥{{ monthlyIncome.toFixed(2) }}</view>
        </view>
      </view>
    </view>

    <!-- 发布费用说明 -->
    <view class="fee-info-card">
      <view class="card-title">发布费用说明</view>
      <view class="fee-list">
        <view class="fee-item">
          <view class="fee-type">出物任务</view>
          <view class="fee-amount">¥5</view>
          <view class="fee-desc">基础发布费</view>
        </view>
        <view class="fee-item">
          <view class="fee-type">求购任务</view>
          <view class="fee-amount">¥4</view>
          <view class="fee-desc">基础发布费</view>
        </view>
        <view class="fee-item">
          <view class="fee-type">快递代拿</view>
          <view class="fee-amount">¥3</view>
          <view class="fee-desc">基础发布费</view>
        </view>
        <view class="fee-item">
          <view class="fee-type">外卖代拿</view>
          <view class="fee-amount">¥2</view>
          <view class="fee-desc">基础发布费</view>
        </view>
        <view class="fee-item">
          <view class="fee-type">其他任务</view>
          <view class="fee-amount">¥3</view>
          <view class="fee-desc">基础发布费</view>
        </view>
        <view class="fee-item urgent">
          <view class="fee-type">加急发布</view>
          <view class="fee-amount">+30%</view>
          <view class="fee-desc">基础费用的30%</view>
        </view>
      </view>
    </view>

    <!-- 充值弹窗 -->
    <uni-popup ref="rechargePopup" type="center" :mask-click="false">
      <view class="recharge-modal">
        <view class="modal-header">
          <view class="modal-title">钱包充值</view>
          <view class="close-btn" @tap="hideRechargeModal">
            <uni-icons type="close" size="20" color="#999" />
          </view>
        </view>

        <view class="recharge-amounts">
          <view class="amount-title">选择充值金额</view>
          <view class="amount-grid">
            <view 
              class="amount-item" 
              v-for="amount in rechargeAmounts" 
              :key="amount.value"
              :class="{ active: selectedAmount === amount.value }"
              @tap="selectAmount(amount.value)"
            >
              <view class="amount-value">¥{{ amount.value }}</view>
              <view class="amount-bonus" v-if="amount.bonus">送¥{{ amount.bonus }}</view>
            </view>
          </view>
        </view>

        <view class="custom-amount">
          <view class="custom-title">自定义金额</view>
          <input 
            type="digit" 
            v-model="customAmount" 
            placeholder="请输入充值金额"
            class="custom-input"
            @input="handleCustomAmount"
          />
        </view>

        <view class="payment-methods">
          <view class="methods-title">选择支付方式</view>
          <view class="method-list">
            <view 
              class="method-item" 
              v-for="method in paymentMethods" 
              :key="method.id"
              :class="{ active: selectedPaymentMethod === method.id }"
              @tap="selectPaymentMethod(method.id)"
            >
              <view class="method-icon">
                <uni-icons :type="method.icon" size="24" :color="method.color" />
              </view>
              <view class="method-info">
                <text class="method-name">{{ method.name }}</text>
                <text class="method-desc">{{ method.desc }}</text>
              </view>
              <view class="method-radio">
                <uni-icons 
                  :type="selectedPaymentMethod === method.id ? 'checkbox-filled' : 'circle'" 
                  size="20" 
                  :color="selectedPaymentMethod === method.id ? '#00BFFF' : '#ddd'" 
                />
              </view>
            </view>
          </view>
        </view>

        <view class="recharge-actions">
          <button class="cancel-btn" @tap="hideRechargeModal">取消</button>
          <button class="confirm-btn" @tap="handleRecharge" :disabled="!canRecharge">
            确认充值 ¥{{ finalAmount.toFixed(2) }}
          </button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userBalance: 0,
      totalIncome: 0,
      monthlyIncome: 0,
      selectedAmount: 50,
      customAmount: '',
      selectedPaymentMethod: 'wechat',
      rechargeAmounts: [
        { value: 10, bonus: 0 },
        { value: 20, bonus: 2 },
        { value: 50, bonus: 8 },
        { value: 100, bonus: 20 },
        { value: 200, bonus: 50 },
        { value: 500, bonus: 150 }
      ],
      paymentMethods: [
        {
          id: 'wechat',
          name: '微信支付',
          desc: '使用微信扫码支付',
          icon: 'chat',
          color: '#07C160'
        },
        {
          id: 'alipay',
          name: '支付宝',
          desc: '使用支付宝支付',
          icon: 'wallet',
          color: '#1677FF'
        }
      ]
    }
  },
  computed: {
    finalAmount() {
      if (this.customAmount && !isNaN(parseFloat(this.customAmount))) {
        return Math.max(0, parseFloat(this.customAmount))
      }
      return this.selectedAmount
    },
    canRecharge() {
      return this.finalAmount > 0 && this.selectedPaymentMethod
    }
  },
  watch: {
    userBalance(newVal, oldVal) {
      if (newVal !== oldVal && oldVal !== 0) {
        uni.showToast({
          title: `余额变动：¥${oldVal.toFixed(2)} → ¥${newVal.toFixed(2)}`,
          icon: 'none',
          duration: 2000
        })
      }
    }
  },
  onLoad() {
    this.loadWalletData()
  },
  onShow() {
    this.loadWalletData()
  },
  methods: {
    // 统一数据加载方法
    async loadWalletData() {
      await Promise.all([
        this.getUserBalance(),
        this.loadIncomeData()
      ])
    },

    // 获取用户余额
    async getUserBalance() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserInfo'
        })
        
        if (res.result && res.result.code === 200) {
          this.userBalance = res.result.data.balance || 0
          
          // 更新本地存储 - 修复存储键名
          const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}
          userInfo.balance = this.userBalance
          uni.setStorageSync('uni-id-pages-userInfo', userInfo)
        }
      } catch (error) {
        console.error('获取用户余额失败：', error)
        uni.showToast({
          title: '获取余额失败',
          icon: 'none'
        })
      }
    },

    // 显示充值弹窗
    showRechargeModal() {
      this.$refs.rechargePopup.open()
    },

    // 隐藏充值弹窗
    hideRechargeModal() {
      this.$refs.rechargePopup.close()
      this.selectedAmount = 50
      this.customAmount = ''
      this.selectedPaymentMethod = 'wechat'
    },

    // 选择充值金额
    selectAmount(amount) {
      this.selectedAmount = amount
      this.customAmount = ''
    },

    // 处理自定义金额输入
    handleCustomAmount() {
      this.selectedAmount = 0
    },

    // 选择支付方式
    selectPaymentMethod(methodId) {
      this.selectedPaymentMethod = methodId
    },

    // 处理充值
    async handleRecharge() {
      if (!this.canRecharge) {
        uni.showToast({
          title: '请选择充值金额和支付方式',
          icon: 'none'
        })
        return
      }

      try {
        uni.showLoading({
          title: '充值中...'
        })

        const res = await uniCloud.callFunction({
          name: 'processPayment',
          data: {
            amount: this.finalAmount,
            paymentMethod: this.selectedPaymentMethod,
            type: 'recharge'
          }
        })

        uni.hideLoading()

        if (res.result.code === 200) {
          uni.showToast({
            title: '充值成功',
            icon: 'success'
          })
          // 充值成功后刷新余额
          await this.refreshUserBalance()
          this.hideRechargeModal()
        } else {
          uni.showToast({
            title: res.result.msg || '充值失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({
          title: '充值失败，请重试',
          icon: 'none'
        })
        console.error('充值失败：', error)
      }
    },

    // 跳转到交易明细
    goToHistory() {
      uni.navigateTo({
        url: '/pages/user/PaymentHistory/PaymentHistory'
      })
    },

    
    // 获取任务收入数据
    async loadIncomeData() {
      try {
        const res = await uniCloud.callFunction({
          name: 'getUserStats'
        });
        
        if (res.result.code === 200) {
          const data = res.result.data;
          this.totalIncome = data.totalIncome || 0;
          this.monthlyIncome = data.monthlyIncome || 0;
        }
      } catch (error) {
        console.error('获取收入数据失败：', error);
        uni.showToast({
          title: '获取收入数据失败',
          icon: 'none'
        })
      }
    },

    // 刷新用户余额 - 简化方法，直接调用getUserBalance
    async refreshUserBalance() {
      await this.getUserBalance()
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 30rpx;
}

.wallet-card {
  background: linear-gradient(135deg, #00BFFF, #0099FF);
  border-radius: 20rpx;
  padding: 40rpx;
  color: #fff;
  margin-bottom: 30rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 153, 255, 0.15);
}

.balance-section {
  text-align: center;
  margin-bottom: 30rpx;
}

.balance-title {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 10rpx;
}

.balance-amount {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 10rpx;
  letter-spacing: 1px;
}

.balance-desc {
  font-size: 14px;
  opacity: 0.8;
}

.wallet-actions {
  display: flex;
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 16px;
  font-weight: 500;
  border: none;
  transition: all 0.3s ease;
}

.action-btn:active {
  transform: scale(0.98);
}

.recharge-btn {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: 2rpx solid rgba(255, 255, 255, 0.3);
}

.history-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 2rpx solid rgba(255, 255, 255, 0.2);
}

.fee-info-card, .income-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  padding-bottom: 15rpx;
  border-bottom: 1px solid #f5f5f5;
}

.fee-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
}

.fee-item {
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  text-align: center;
  transition: all 0.2s ease;
}

.fee-item:active {
  transform: scale(0.98);
}

.fee-item.urgent {
  background: #fff3cd;
  border: 2rpx solid #ffc107;
}

.fee-type {
  font-size: 14px;
  color: #666;
  margin-bottom: 8rpx;
}

.fee-amount {
  font-size: 18px;
  font-weight: 600;
  color: #FF9F1C;
  margin-bottom: 4rpx;
}

.fee-desc {
  font-size: 12px;
  color: #999;
}

.recharge-modal {
  width: 600rpx;
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  padding: 10rpx;
  transition: all 0.2s ease;
}

.close-btn:active {
  transform: scale(0.85);
}

.recharge-amounts {
  margin-bottom: 30rpx;
}

.amount-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.amount-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15rpx;
}

.amount-item {
  padding: 20rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  text-align: center;
  transition: all 0.3s ease;
}

.amount-item.active {
  border-color: #00BFFF;
  background: #f0f8ff;
}

.amount-item:active {
  transform: scale(0.95);
}

.amount-value {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4rpx;
}

.amount-bonus {
  font-size: 12px;
  color: #FF4D4F;
}

.custom-amount {
  margin-bottom: 30rpx;
}

.custom-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 15rpx;
}

.custom-input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  padding: 0 20rpx;
  font-size: 16px;
  box-sizing: border-box;
}

.custom-input:focus {
  border-color: #00BFFF;
  outline: none;
}

.payment-methods {
  margin-bottom: 30rpx;
}

.methods-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.method-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  margin-bottom: 15rpx;
  border: 2rpx solid #f0f0f0;
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.method-item.active {
  border-color: #00BFFF;
  background: #f0f8ff;
}

.method-item:active {
  background: #f5f9ff;
}

.method-icon {
  margin-right: 20rpx;
}

.method-info {
  flex: 1;
}

.method-name {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4rpx;
}

.method-desc {
  font-size: 12px;
  color: #999;
}

.method-radio {
  margin-left: 20rpx;
}

/* 收入统计卡片样式 */
.income-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.income-item {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  margin: 0 10rpx;
}

.income-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8rpx;
}

.income-amount {
  font-size: 20px;
  font-weight: 600;
  color: #00BFFF;
}


.detail-btn {
  background: #00BFFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 12rpx 24rpx;
  font-size: 14px;
  transition: all 0.2s ease;
}

.detail-btn:active {
  background: #0099FF;
}

.recharge-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 16px;
  font-weight: 500;
  border: none;
  transition: all 0.2s ease;
}

.cancel-btn:active, .confirm-btn:active {
  transform: scale(0.98);
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background: linear-gradient(135deg, #00BFFF, #0099FF);
  color: #fff;
}

.confirm-btn:disabled {
  background: #ccc;
  color: #999;
  cursor: not-allowed;
}
</style>
